﻿using System;
using System.Net;
using System.Threading;
using xxpl.GAE;

namespace xxpl.HTTP
{
    public class RequestDispacther
    {
        private class Task
        {
            private HttpListenerContext context;
            private IHttpRequestHandler handler;

            public Task(IHttpRequestHandler handler, HttpListenerContext context)
            {
                this.handler = handler;
                this.context = context;
            }

            public void ExecuteHanlder(object state)
            {
                handler.Execute(context.Request, context.Response);
            }
        }

        public void DispatchRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;

            IHttpRequestHandler handler = Createhandler(request);

            Task task = new Task(handler, context);

            ThreadPool.QueueUserWorkItem(task.ExecuteHanlder);
        }

        private static IHttpRequestHandler Createhandler(HttpListenerRequest request)
        {
            if (request.Url.IsLoopback)
            {
                if (request.RawUrl.IndexOf("/report", StringComparison.CurrentCultureIgnoreCase) > -1)
                {
                    return new ServiceInfoHandler();
                }
            }
            else
            {
                return new SimpleRequestHandler2();
            }

            return new NullHandler();
        }
    }
}
